<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Waterfall</title>
    <style>
        img {
            width: 400px;
            vertical-align: top;
            padding: 5px;
        }
    </style>
</head>
<body>

<div class="box">
    <img src="img/1.jpg" alt="">
    <img src="img/2.jpg" alt="">
    <img src="img/3.jpg" alt="">
    <img src="img/4.jpg" alt="">
    <img src="img/5.jpg" alt="">
    <img src="img/6.jpg" alt="">
    <img src="img/7.jpg" alt="">
    <img src="img/8.jpg" alt="">
    <img src="img/9.jpg" alt="">
    <img src="img/10.jpg" alt="">

</div>

<script src="js/jquery-2.0.0.min.js"></script>
<script>
    $(function () {

        //获取图片的宽度
        let imgWidth = $('img').outerWidth();

        waterFall();

        function waterFall() {
            //根据浏览器宽度确定每行图片的列数
            let column = parseInt($(window).width() / imgWidth)
            let heightArr = [];
            //高度数组的第一行图片高度初始化
            for (let i = 0; i < column; i++) {
                heightArr[i] = 0;
            }
                //遍历页面所有图片元素，逐一将其定位
            $.each($('img'), function (index, item) {
                // 当前元素的高度
                let itemHeight = $(item).outerHeight();
                // 高度数组最小的高度
                let minHeight = Math.min(...heightArr);
                // 高度数组最小的高度的索引
                let minIndex = heightArr.indexOf(minHeight);
                $(item).css({
                    position: 'absolute',
                    top: minHeight + 'px',
                    left: minIndex * imgWidth + 'px'
                });
                console.log("index "+index)
                console.log("itemHeight "+itemHeight)
                console.log("heightArr "+heightArr)
                console.log("minHeight "+minHeight)
                console.log("minIndex "+minIndex)
                console.log("top "+minHeight)
                console.log("left "+minIndex * imgWidth)

                heightArr[minIndex] += itemHeight;


                console.log("heightArr "+heightArr)

            })

        }

        $(window).resize(function () {
            waterFall();
        })
    })
</script>

</body>
</html>